package com.example.victory.service;

import com.example.victory.config.ServiceError;
import com.example.victory.mapper.CustomerMapper;
import com.example.victory.swagger.AppApiDelegate;
import com.example.victory.swagger.model.ApiRequestCustomerRelationInfo;
import com.example.victory.swagger.model.ApiResponseCustomerRelationInfo;
import com.example.victory.swagger.model.ApiResponseCustomerRelationInfoData;
import com.example.victory.swagger.model.ApiResponseCustomerRelationInfoDataCustomers;
import com.cgws.fintech.sdk.api.inner.security.model.User;
import com.cgws.fintech.sdk.api.mvp.model.ApiRequestQueryCustomerAuth;
import com.cgws.fintech.sdk.api.mvp.model.ApiResponseQueryCustomerAuth;
import com.cgws.fintech.sdk.api.mvp.model.ResponseQueryCustomerAuthList;
import com.cgws.fintech.sdk.common.exception.GlobalException;
import com.cgws.fintech.sdk.common.utils.JsonHelper;
import com.example.victory.common.web.ServiceHelper;
import com.cgws.fintech.sdk.inner.utils.web.SessionService;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class AppApiService implements AppApiDelegate {

	@Autowired
	private SessionService sessionService;
	@Autowired
	private CustomerMapper customerMapper;
	@Autowired
	private MvpLoginService mvpLoginService;


	private Integer getCustomerAccount(User user) {
		String crmId = user.getCrmId();
		if (StringUtils.isEmpty(crmId)) {
			throw new GlobalException(ServiceError.ACCOUNT_NOT_EXISTS);
		}
		return Integer.parseInt(crmId);

	}

	@Override
	public ResponseEntity<ApiResponseCustomerRelationInfo> getCustomerRelationInfo(ApiRequestCustomerRelationInfo param) {
		ServiceHelper.checkDataNotNull(param.getData(), "data");
		String fcid = param.getData().getFcid();
		ServiceHelper.checkDataNotNull(fcid, "fcid");
		User user = sessionService.getCurrentUserSession(true).getUser();
		Integer accountId = getCustomerAccount(user);

		//得到手机号
		String phone = fcid.replace("@", "").replace(":cust.cgws.com.cn", "");
		ApiRequestQueryCustomerAuth queryCustomerAuth = new ApiRequestQueryCustomerAuth();
		queryCustomerAuth.setFCID(phone);
		ResponseEntity<ApiResponseQueryCustomerAuth> queryCustomerAuthResponseEntity = null;
		try {
			queryCustomerAuthResponseEntity = mvpLoginService.queryCustomerAuth(queryCustomerAuth);
		} catch (Exception ex) {
			throw new GlobalException(ServiceError.QUERY_CUSTOMER_STATUS);
		}
		List<String> accountList = new ArrayList<>();
		if (queryCustomerAuthResponseEntity.getStatusCode() == HttpStatus.OK) {
			List<ResponseQueryCustomerAuthList> queryCustomerAuthLists = queryCustomerAuthResponseEntity.getBody().getData().getList();
			if (queryCustomerAuthLists != null && queryCustomerAuthLists.size() > 0) {
				queryCustomerAuthLists.stream().forEach(customerAuth -> {
					accountList.add(customerAuth.getCustNum());
				});
			}
		} else {
			log.error("从凡泰查询客户授权出错:{}", queryCustomerAuthResponseEntity);
		}
		List<ApiResponseCustomerRelationInfoDataCustomers> customerRelationInfoCustomer = null;
		if (accountList.size() > 0) {
			customerRelationInfoCustomer = customerMapper.queryCustomerGeneralInfo(accountList);
			if (customerRelationInfoCustomer != null && customerRelationInfoCustomer.size() > 0) {
				customerRelationInfoCustomer.stream().forEach(customers -> {
					List<Integer> gxlxList = customerMapper.queryCustomerGxlxByCustomerId(customers.getCustomerId(), accountId);
					if (gxlxList != null && gxlxList.size() > 0) {
						if (gxlxList.contains(10)) {
							customers.setRelationType("10");
						} else if (gxlxList.contains(2)) {
							customers.setRelationType("2");
						} else if (gxlxList.contains(1)) {
							customers.setRelationType("1");
						}
					}

					HashMap<String, Object> nativeBean = Maps.newHashMap();
					nativeBean.put("identity", "customerPanoramic");
					List<Map> paramInfo = new ArrayList<>();
					HashMap<String, String> keyValueMap = Maps.newHashMap();
					keyValueMap.put("key", "customerId");
					keyValueMap.put("value", customers.getCustomerId());
					paramInfo.add(keyValueMap);
					nativeBean.put("paramInfo", paramInfo);
					HashMap<String, Object> jumpUrlMap = Maps.newHashMap();
					jumpUrlMap.put("type", "native");
					jumpUrlMap.put("nativeBean", nativeBean);

					if (param.getAppPlatform().equalsIgnoreCase("ios") && (param.getAppVerName().equalsIgnoreCase("1.0.0") || param.getAppVerName().equalsIgnoreCase("1.0.1"))) {
						jumpUrlMap.clear();
						HashMap<String, String> paramInfoMap = Maps.newHashMap();
						paramInfoMap.put("customerId", customers.getCustomerId());
						paramInfoMap.put("page", "CustomerDetail");
						HashMap<String, String> rnBeanMap = Maps.newHashMap();
						rnBeanMap.put("bundleId", "com.cgws.meppo.customermanagement");
						rnBeanMap.put("displayName", "客户详情");
						rnBeanMap.put("iconUrl", "https://fintechapp-test-1258285289.cos.ap-guangzhou.myqcloud.com/app/a/2019-02/1551317630558-8722ddc24f144858bf9f8fa6486ef1a9.png");
						rnBeanMap.put("paramInfo", JsonHelper.toJson(paramInfoMap));
						jumpUrlMap.put("type", "rn");
						jumpUrlMap.put("rnBean", rnBeanMap);
					}

					customers.setJumUrl(JsonHelper.toJson(jumpUrlMap));
				});
			}
		}
		if (customerRelationInfoCustomer == null || customerRelationInfoCustomer.size() == 0) {
			log.info("im聊天框顶部查询客户关系无数据，客户经理:{},客户fcid:{}, 凡泰返回数据:{}, 处理后得到的查询列表:{}", accountId, fcid, customerRelationInfoCustomer, accountList);
		}
		return ResponseEntity.ok(new ApiResponseCustomerRelationInfo().data(new ApiResponseCustomerRelationInfoData().customers(customerRelationInfoCustomer)));
	}
}
